package com.wondertek.poms.search.controller;

import com.wondertek.oes.sso.client.service.sso.SsoRemoteService;
import com.wondertek.oes.sso.common.model.resp.GroupInfoResp;
import com.wondertek.poms.common.constant.CurrentUser;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.dao.po.BcInfo;
import com.wondertek.poms.dao.po.ContentBaseFee;
import com.wondertek.poms.dao.po.ContentFee;
import com.wondertek.poms.dao.po.PrdInfo;
import com.wondertek.poms.dao.po.es.ContentVo;
import com.wondertek.poms.dao.repo.IBcInfoDao;
import com.wondertek.poms.dao.repo.IPrdInfoDao;
import com.wondertek.poms.search.service.IContentBaseFeeService;
import com.wondertek.poms.search.service.IContentFeeService;
import com.wondertek.poms.search.service.IPrdContESService;
import com.wondertek.poms.search.vo.PrdContESVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenjijiang
 * @description
 */
@RestController
@RequestMapping("prdcont-es")
@Slf4j
public class PrdContESController {

	@Autowired
	private IBcInfoDao bcInfoDao;
	@Autowired
	private IPrdContESService iPrdContESService;

	@Autowired
	private SsoRemoteService ssoRemoteService;
	@Autowired
	private IPrdInfoDao prdInfoDao;
	@Autowired
	private IContentFeeService contentFeeService;
	@Autowired
	private IContentBaseFeeService contentBaseFeeService;

	@GetMapping("/list")
	public ResultBean list(PrdContESVo prdContESVo, HttpServletRequest request,
	                       @RequestParam(defaultValue = "1") int page,
	                       @RequestParam(defaultValue = "0") int start,
	                       @RequestParam(defaultValue = "20") int rows) {
		Map<String, Object> map = new HashMap<>();
		String prdInfoId = prdContESVo.getPrdInfoId();
		String packageId = prdContESVo.getPackageId();
		if (StringUtils.isBlank(prdInfoId) && StringUtils.isBlank(packageId)) {
			map.put("count", 0);
			map.put("data", null);
			return ResultBean.ok(map);
		}
		Map<String, Object> paraMap = new HashMap<>();
		List<ContentVo> contentVoList = new ArrayList<ContentVo>();
		paraMap.put("createTime", prdContESVo.getCreateTime());
		paraMap.put("startTime", prdContESVo.getStartTime());
		paraMap.put("endTime", prdContESVo.getEndTime());
		paraMap.put("packageId", prdContESVo.getPackageId());
		paraMap.put("selectType", prdContESVo.getSelectType());
		paraMap.put("selectProInfoId", prdContESVo.getSelectProInfoId());
		paraMap.put("releaseTime", prdContESVo.getReleaseTime());
		paraMap.put("cpId", prdContESVo.getCpId());
		paraMap.put("charge", prdContESVo.getCharge());
		paraMap.put("keywords", prdContESVo.getKeywords());
		paraMap.put("bcStatus", prdContESVo.getBcStatus());
		paraMap.put("disStatus", prdContESVo.getDisStatus());
		paraMap.put("pubStatus", prdContESVo.getPubStatus());
		paraMap.put("contentId", prdContESVo.getContentId());
		paraMap.put("firstLabel", prdContESVo.getFirstLabel());
		String contentName = prdContESVo.getContentName();
		paraMap.put("contentName", contentName);
		paraMap.put("status", prdContESVo.getStatus());
		paraMap.put("copyRightType", prdContESVo.getCopyRightType());
		paraMap.put("scopeOfAuthor", prdContESVo.getScopeOfAuthor());
		paraMap.put("firstClassify", prdContESVo.getFirstClassify());
		String secondClassify = prdContESVo.getSecondClassify();
		paraMap.put("secondClassify", secondClassify);
		paraMap.put("bcType", prdContESVo.getBcType());
		paraMap.put("gslbStatus", prdContESVo.getGslbStatus());
		paraMap.put("cdnStatus", prdContESVo.getCdnStatus());
		paraMap.put("cacheCdnStatus", prdContESVo.getCacheCdnStatus());
		paraMap.put("viewType", prdContESVo.getViewType());
		paraMap.put("vomsPublish", prdContESVo.getVomsPublish());
		paraMap.put("formType", prdContESVo.getFormType());
		paraMap.put("albumStatus", prdContESVo.getAlbumStatus());
		paraMap.put("price", prdContESVo.getPrice());
		paraMap.put("area", prdContESVo.getArea());
		paraMap.put("prdContXT", prdContESVo.getPrdContXT());
		paraMap.put("contCatergry", prdContESVo.getContCatergry());
		paraMap.put("saleCategory", prdContESVo.getSaleCategory());
		paraMap.put("orderFlag", prdContESVo.getOrderFlag());
		paraMap.put("displaySubSet", prdContESVo.getDisplaySubSet());
		paraMap.put("shieldDelCont", prdContESVo.getShieldDelCont());
		paraMap.put("channelPackageId", prdContESVo.getChannelPackageId());
		paraMap.put("optimal", prdContESVo.getOptimal());
		paraMap.put("recommendation", prdContESVo.getRecommendation());
		paraMap.put("copy", prdContESVo.getCopy());
		paraMap.put("accessPlatFormType", prdContESVo.getAccessPlatFormType());
		paraMap.put("serialSequence", prdContESVo.getSerialSequence());

		paraMap.put("equityId", prdContESVo.getEquityId());
		paraMap.put("productId", prdContESVo.getProductId());
		paraMap.put("mpid", prdContESVo.getMpid());
		paraMap.put("MiguDBID", prdContESVo.getMiguDBID());
		paraMap.put("mvid", prdContESVo.getMvid());
		paraMap.put("mcid", prdContESVo.getMcid());
		paraMap.put("author", prdContESVo.getAuthor());
		paraMap.put("assist", prdContESVo.getAssist());
		paraMap.put("createTimeBegin", prdContESVo.getCreateTimeBegin());
		paraMap.put("createTimeEnd", prdContESVo.getCreateTimeEnd());

		// 按一级分类，推荐标签，版权信息区分播控 start
		if (StringUtils.isNotBlank(prdContESVo.getBcStatus()) && prdContESVo.getBcStatus().equals("0")) {
			BcInfo bcInfoByUser = null;
			BcInfo bcInfoByGroup = null;
			Long userId = CurrentUser.currUserId();
			List<GroupInfoResp> groups = ssoRemoteService.getGroupInfoByUser(request, null, null);
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i < groups.size(); i++) {
				if (i == groups.size() - 1) {
					buffer.append(groups.get(i).getGroupId());
				}
				buffer.append(groups.get(i).getGroupId() + ",");
			}
			String groupIds = buffer.toString();
			StringBuffer fisrtClassifys = new StringBuffer();
			StringBuffer copyRightCpIds = new StringBuffer();
			StringBuffer recommendations = new StringBuffer();
			String fisrtClassifysStr = "";
			String copyRightCpIdsStr = "";
			String recommendationsStr = "";
			if (userId != null) {
				bcInfoByUser = bcInfoDao.findByUserId(userId);
				if (bcInfoByUser != null) {
					if (!StringUtil.isNullStr(bcInfoByUser
							.getFirstClassify())) {
						fisrtClassifys.append(",").append(
								bcInfoByUser.getFirstClassify());
					}
					if (!StringUtil.isNullStr(bcInfoByUser
							.getCopyRightCpId())) {
						copyRightCpIds.append(",").append(
								bcInfoByUser.getCopyRightCpId());
					}
					if (!StringUtil.isNullStr(bcInfoByUser
							.getRecommendation())) {
						recommendations.append(",").append(
								bcInfoByUser.getRecommendation());
					}
				}
			}
			if (!StringUtil.isNullStr(groupIds)) {
				List<BcInfo> bcInfosByGroup = bcInfoDao
						.findAllByGroups(groupIds);
				if (bcInfosByGroup != null) {
					for (int i = 0; i < bcInfosByGroup.size(); i++) {
						BcInfo bcInfo = bcInfosByGroup.get(i);
						if (!StringUtil
								.isNullStr(bcInfo.getFirstClassify())) {
							fisrtClassifys.append(",").append(
									bcInfo.getFirstClassify());
						}
						if (!StringUtil
								.isNullStr(bcInfo.getCopyRightCpId())) {
							copyRightCpIds.append(",").append(
									bcInfo.getCopyRightCpId());
						}
						if (!StringUtil.isNullStr(bcInfo
								.getRecommendation())) {
							recommendations.append(",").append(
									bcInfo.getRecommendation());
						}
					}
				}
			}
			if (fisrtClassifys.length() > 0) {
				fisrtClassifysStr = fisrtClassifys.substring(1);
			}
			if (copyRightCpIds.length() > 0) {
				copyRightCpIdsStr = copyRightCpIds.substring(1);
			}
			if (recommendations.length() > 0) {
				recommendationsStr = recommendations.substring(1);
			}
			if (!StringUtil.isNullStr(fisrtClassifysStr)) {
				map.put("firstClassifys", fisrtClassifysStr);
				log.info("=====================firstClassifys:"
						+ fisrtClassifysStr + "=======================");
			}
			if (!StringUtil.isNullStr(copyRightCpIdsStr)) {
				map.put("copyRightCpIds", copyRightCpIdsStr);
				log.info("=====================copyRightCpIds:"
						+ copyRightCpIdsStr + "=======================");
			}
			if (!StringUtil.isNullStr(recommendationsStr)) {
				map.put("recommendations", recommendationsStr);
				log.info("=====================recommendationsStr:"
						+ recommendationsStr + "=======================");
			}
		}
		if (!StringUtil.isNullStr(contentName)) {
			log.info("内容名称:" + contentName);//查看内容名称传输过来后是否存在编码问题
		}
		if (!StringUtil.isNullStr(secondClassify)) {
			log.info("二级分类:" + secondClassify);//查看内容名称传输过来后是否存在编码问题
		}
		// 按一级分类，推荐标签，版权信息区分播控 End
		long count = iPrdContESService.getContentCountByMap(map, StringUtil.nullToLong(prdInfoId));

		if (count > 0) {
			contentVoList = iPrdContESService.getContentList(map, Integer.valueOf(start), Integer.valueOf(rows),
					StringUtil.nullToLong(prdInfoId));

			for (ContentVo vo : contentVoList) {
				Long infoId = vo.getPrdInfoId();
				Long prdContId = vo.getPrdContId();
				List<ContentFee> list = new ArrayList<ContentFee>();
				if (vo.getSalConfigPrice() != null) {
					if (vo.getSalConfigPrice().equals("0")) {
						vo.setSalConfigPrice("免费");
					} else {
						vo.setSalConfigPrice(Float.parseFloat(vo
								.getSalConfigPrice()) / 100 + "元/次");
					}
				} else if (vo.getSalConfigPrice() == null
						|| vo.getSalConfigPrice().equals("")) {
					PrdInfo prdInfo = prdInfoDao.findByPrdInfoId(infoId);
					if (!StringUtil.isNullStr(prdInfo.getFreeType())) {
						vo.setSalConfigPrice("免费");
					} else {
						String monthPrice = prdInfo.getMonthPrice();
						String numberPrice = prdInfo.getNumberPrice();
						if (!StringUtil.isNullStr(monthPrice)
								|| !StringUtil.isNullStr(numberPrice)) {
							StringBuffer buff = new StringBuffer("");
							if (!StringUtil.isNullStr(numberPrice)) {
								buff.append(Float.parseFloat(numberPrice)
										/ 100 + "元/次  ");
							}
							if (!StringUtil.isNullStr(monthPrice)) {
								buff.append(Float.parseFloat(monthPrice)
										/ 100 + "元/月");
							}
							vo.setSalConfigPrice(buff.toString());
						}
					}
				} else {
					vo.setSalConfigPrice(null);
				}

				list = contentFeeService.queryContentFee(
						infoId.toString(), prdContId.toString());
				vo.setSalPromPrice("");// 基本促销计费
				StringBuffer chanelPkgSalBuf = new StringBuffer("");
				String chanelPkgSalStr = "";// 渠道促销计费
				for (ContentFee fee : list) {
					String str = "";
					Integer l = fee.getSaleCategory();

					String type = fee.getType().toString();

					/*
					 * if(fee.getType() ==0){ str = "包月"; }
					 */
					String discount = fee.getDiscount();
					if (discount == null || discount.equals("")) {
						discount = "10";
					}
					if (l == 1) {
						vo.setSalPromPrice(vo.getSalPromPrice() + str
								+ "预售:" + Integer.parseInt(fee.getPrice())
								* 0.001 * Integer.parseInt(discount)
								+ "元/次  ");
						if ("2".equals(type)
								&& fee.getChannelPackageId() != null) {
							chanelPkgSalBuf.append(fee
									.getChannelPackageId()
									+ "-预售:"
									+ Integer.parseInt(fee.getPrice())
									* 0.001
									* Integer.parseInt(discount)
									+ "元/次 ,");
						}
					}
					if (l == 2) {
						vo.setSalPromPrice(vo.getSalPromPrice() + str
								+ "预订:" + Integer.parseInt(fee.getPrice())
								* 0.001 * Integer.parseInt(discount)
								+ "元/次  ");
						if ("2".equals(type)
								&& fee.getChannelPackageId() != null) {
							chanelPkgSalBuf.append(fee
									.getChannelPackageId()
									+ "-预订:"
									+ Integer.parseInt(fee.getPrice())
									* 0.001
									* Integer.parseInt(discount)
									+ "元/次 ,");
						}
					}
					if (l == 3) {
						vo.setSalPromPrice("免费");
						if ("2".equals(type)
								&& fee.getChannelPackageId() != null) {
							chanelPkgSalBuf.append(fee
									.getChannelPackageId() + "-限免,");
						}
					}
					if (l == 4) {
						vo.setSalPromPrice(vo.getSalPromPrice() + str
								+ "渠道打折:"
								+ Integer.parseInt(fee.getPrice()) * 0.001
								* Integer.parseInt(discount) + "元/次  ");
						if ("2".equals(type)
								&& fee.getChannelPackageId() != null) {
							chanelPkgSalBuf.append(fee
									.getChannelPackageId()
									+ "-渠道打折:"
									+ Integer.parseInt(fee.getPrice())
									* 0.001
									* Integer.parseInt(discount)
									+ "元/次 ,");
						}
					}
				}
				chanelPkgSalStr = chanelPkgSalBuf.toString();
				if (chanelPkgSalStr.length() > 0) {
					vo.setChanelPkgSalPrice(chanelPkgSalStr.substring(0,
							chanelPkgSalStr.length() - 1));
				}
				// 渠道基本计费
				List<ContentBaseFee> baseList = new ArrayList<ContentBaseFee>();
				baseList = contentBaseFeeService.queryContentBaseFee(
						prdInfoId, prdContId);
				if (baseList != null && baseList.size() > 0) {
					StringBuffer buf = new StringBuffer("");
					String chanelPkgIdStr = "";
					for (ContentBaseFee baseFee : baseList) {
						// vo.setChannelPackageId(baseFee.getChannelPackageId());
						// chanelPkgIdStr += baseFee.getChannelPackageId() +
						// ",";
						if ("0".equals(baseFee.getOrderFlag())) {
							buf.append(baseFee.getChannelPackageId() + "-"
									+ Float.parseFloat(baseFee.getPrice())
									/ 100 + "元/月,");
						} else if ("1".equals(baseFee.getOrderFlag())) {
							buf.append(baseFee.getChannelPackageId() + "-"
									+ Float.parseFloat(baseFee.getPrice())
									/ 100 + "元/次,");
						} else if ("7".equals(baseFee.getOrderFlag())) {
							buf.append(baseFee.getChannelPackageId() + "-"
									+ "免费,");
						}
					}
					chanelPkgIdStr = buf.toString();
					vo.setChannelPkgPrice(chanelPkgIdStr.substring(0,
							chanelPkgIdStr.length() - 1));
				}

			}
		}

		map.put("count", count);
		map.put("data", contentVoList);
		return ResultBean.ok(map);
	}
}
